import { HttpException, Injectable } from '@nestjs/common';
import { Express } from 'express';
import * as qiniu from 'qiniu';

@Injectable()
export class uploadUtil {
  private config = new qiniu.conf.Config();
  private accessKey = 'dUFvyT1ZRGsMLWG1XoeZS73h_NUnCw1GmCNdwbl_';
  private secretKey = 'hVdIe_i_oxlcTe7zkOMMek2Wtb6HFuiU-z_wYqpK';

  private mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);
  private options = {
    scope: 'taobaoh5',
    expires: 7200,
  };
  private putPolicy = new qiniu.rs.PutPolicy(this.options);
  private formUploader = new qiniu.form_up.FormUploader(this.config);
  private uploadToken = this.putPolicy.uploadToken(this.mac);
  private putExtra = new qiniu.form_up.PutExtra();
  async upload(file :Buffer,fileName:string) {
    console.log(this.uploadToken,'token')
  return await new Promise((res,rej)=>{
      this.formUploader.put(this.uploadToken,fileName,file,this.putExtra,(err,resBody,resInfo)=>{
        if (err) {
          throw err;
        }
        if (resInfo.statusCode == 200) {
            res({
              code:1,
              message:'上传成功',
              data:{
                url:'upload.plover.games/'+resBody.key
              }
            })
        } else { 
           throw new HttpException({
            code:1,
            message:'上传失败'
           },200)
        }
      })
    })
   
   
  }
}
// config.zone = 'qiniu.zone.Zone_z0'
// private formUploader = new qiniu.form_up.FormUploader(config);
// private putExtra = new qiniu.form_up.PutExtra();
// formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
//   respBody, respInfo) {
//   if (respErr) {
//     throw respErr;
//   }
//   if (respInfo.statusCode == 200) {
//     console.log(respBody);
//   } else {
//     console.log(respInfo.statusCode);
//     console.log(respBody);
//   }
// });
